package com.hibase.quartz.utils;

import com.hibase.quartz.config.SingleScheduler;
import com.hibase.quartz.config.annotation.MdsJobHandler;
import com.hibase.quartz.entity.MdsJobHandlerEntity;
import com.hibase.quartz.service.MdsJobService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.*;

/**
 * <p>
 * 任务扫描器
 * </p>
 *
 * @author LYL
 * @since 2020-11-18
 */
@Slf4j
@Component
public class JobHandlerScanner implements ApplicationContextAware, InitializingBean {


    @Autowired
    private SingleScheduler singleScheduler;

    @Autowired
    private MdsJobService mdsJobService;

    private ApplicationContext applicationContext;

    private List<MdsJobHandlerEntity> jobHandlerEntityList = new ArrayList<>();

    public boolean init() {

        try {

            Map<String, Object> annotatedBeansMap = applicationContext.getBeansWithAnnotation(MdsJobHandler.class);

            for (Object o : annotatedBeansMap.values()) {

                Class p = o.getClass();

                MdsJobHandlerEntity entity = new MdsJobHandlerEntity();

                Annotation annotation = p.getAnnotation(MdsJobHandler.class);

                Method method = annotation.getClass().getDeclaredMethod("value", null);

                entity.setBeanName(String.valueOf(method.invoke(annotation, null)));

                entity.setClassName(p.getName());

                jobHandlerEntityList.add(entity);

            }

            return true;

        } catch (Exception e) {

            log.error("初始化定时任务扫描器失败！{}",e.getMessage());

            return false;

        }

    }

    public List<MdsJobHandlerEntity> getJobHandlerEntityList() {

        return this.jobHandlerEntityList;
    }



    @Override
    public void afterPropertiesSet() throws Exception {

        //初始化 所有JobHandler
        if (this.init()) {

            //初始化启动所有的Job
            try {

                //启动时创建私有任务调度器
                singleScheduler.init();

                mdsJobService.reStartAllJobs();

                log.info(" MdsJob init success");

            } catch (SchedulerException e) {

                log.error(" MdsJob init error!");

                e.printStackTrace();

            }
        }

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext = applicationContext;

    }

}